package cfdt.common.exception.handler;

import cfdt.common.enums.CommonCodeEnum;
import cfdt.tools.json.JsonUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.validation.BindException;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import cfdt.common.vo.ObjectBaseResponse;
import cfdt.common.exception.CodeException;



@ControllerAdvice
@RestControllerAdvice
public class GlobalExceptionHandler {

    private Logger logger = LoggerFactory.getLogger(getClass());

    @ExceptionHandler(value = { NullPointerException.class })
    public ObjectBaseResponse NullPointerException(NullPointerException e) {
        logger.error("", e);
        return ObjectBaseResponse.error(CommonCodeEnum.CODE_0002);
    }

    @ExceptionHandler(value = { CodeException.class })
    public ObjectBaseResponse CodeException(CodeException e) {
        ObjectBaseResponse response = new ObjectBaseResponse(e.getCode(), e.getMessage());
        logger.error("response: {}", JsonUtil.toJsonStr(response));
        return response;
    }

    /**
     * POST请求参数校验异常
     */
    @ExceptionHandler(value = { MethodArgumentNotValidException.class })
    public ObjectBaseResponse MethodArgumentNotValidException(MethodArgumentNotValidException e) {
        String message = e.getBindingResult().getAllErrors().stream()
                .findFirst()
                .map(ObjectError::getDefaultMessage)
                .orElse("参数校验失败");
        logger.error("参数校验失败: {}", message, e);
        return ObjectBaseResponse.error(CommonCodeEnum.CODE_9999, message);
    }

    /**
     * GET请求参数校验异常
     */
    @ExceptionHandler(value = { BindException.class })
    public ObjectBaseResponse BindException(BindException e) {
        String message = e.getBindingResult().getAllErrors().stream()
                .findFirst()
                .map(ObjectError::getDefaultMessage)
                .orElse("参数绑定失败");
        logger.error("参数绑定异常: {}", message, e);
        return ObjectBaseResponse.error(CommonCodeEnum.CODE_9999, e.getMessage());
    }


    @ExceptionHandler(value = { Exception.class })
    public ObjectBaseResponse Exception(Exception e) {
        logger.error("系统异常", e);
        return ObjectBaseResponse.error(CommonCodeEnum.CODE_9998);
    }

}
